from rest_framework.authtoken.models import Token
from django.contrib.auth.views import LogoutView

from rest_framework.permissions import AllowAny
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.contrib.auth import authenticate

from django.contrib.auth.password_validation import validate_password
from django.core.exceptions import ValidationError
from rest_framework_simplejwt.tokens import RefreshToken
import re
from users.models import CustomUser
from users.serializers import UserSerializer


def is_valid_username(username):
    # 使用正则表达式匹配用户名是否只包含字母和数字
    pattern = r'^[a-zA-Z0-9]+$'
    if not re.match(pattern, username):
        return False
    return True


class UserRegisterView(APIView):
    permission_classes = [AllowAny]

    def post(self, request):
        # 去除参数空格
        real_name = request.data.get('real_name').strip()
        phone = request.data.get('phone').strip()
        username = request.data.get('username').strip()
        password = request.data.get('password').strip()
        role = request.data.get('role')

        # 检查用户名是否为中文及符号
        if not is_valid_username(username):
            return Response({'error': '用户名只能由字母和数字组成'}, status=status.HTTP_400_BAD_REQUEST)
        # 检查真实姓名长度是否在2-16之间
        if len(real_name) < 2 or len(real_name) > 16:
            return Response({'error': '真实姓名长度必须在2-16之间'}, status=status.HTTP_400_BAD_REQUEST)
        # # 检查用户名长度是否在3-16之间
        # if len(username) < 3 or len(username) > 16:
        #     return Response({'error': '用户名长度必须在3-16之间'}, status=status.HTTP_400_BAD_REQUEST)
        #
        # # 检查手机号是否为11位数字
        # if not phone.isdigit() or len(phone) != 11:
        #     return Response({'error': '手机号格式错误'}, status=status.HTTP_400_BAD_REQUEST)
        #
        # # 检查真实姓名是否为中文
        # if not real_name.isalpha():
        #     return Response({'error': '真实姓名只能由中文组成'}, status=status.HTTP_400_BAD_REQUEST)
        # # 检查真实姓名长度是否在2-16之间
        # if len(real_name) < 2 or len(real_name) > 16:
        #     return Response({'error': '真实姓名长度必须在2-16之间'}, status=status.HTTP_400_BAD_REQUEST)
        #
        # # 检查角色是否有效
        # if role not in [0, 1]:
        #     return Response({'error': '角色无效'}, status=status.HTTP_400_BAD_REQUEST)
        #
        # # 检查密码是否符合要求
        # try:
        #     validate_password(password)
        # except ValidationError as e:
        #     return Response({'error': e.messages}, status=status.HTTP_400_BAD_REQUEST)
        #
        # # 创建新用户
        # user = CustomUser(username=username, real_name=real_name, phone=phone, role=role)
        # user.set_password(password)
        # user.save()

        # 检查用户名是否已经存在
        if CustomUser.objects.filter(username=username).exists():
            return Response({'error': '用户名已存在'}, status=status.HTTP_400_BAD_REQUEST)

        # 检查手机号是否已经存在
        if CustomUser.objects.filter(phone=phone).exists():
            return Response({'error': '手机号已存在'}, status=status.HTTP_400_BAD_REQUEST)

        # 检查密码是否符合要求
        try:
            validate_password(password)
        except ValidationError as e:
            return Response({'error': e.messages}, status=status.HTTP_400_BAD_REQUEST)

        # 创建新用户
        user = CustomUser(real_name=real_name, phone=phone, username=username, role=role)
        user.set_password(password)
        user.save()

        return Response({'message': '注册成功'}, status=status.HTTP_201_CREATED)


class UserLoginView(APIView):
    permission_classes = [AllowAny]

    def post(self, request):
        # 去除参数空格
        username = request.data.get('username').strip()
        password = request.data.get('password').strip()

        if not username or not password:
            return Response({'error': "用户名或密码不能为空"}, status=status.HTTP_400_BAD_REQUEST)

        # 验证用户身份
        user = authenticate(username=username, password=password)
        if user is not None:
            # 生成JWT 刷新token
            refresh_token = RefreshToken.for_user(user)
            access_token = str(refresh_token.access_token)

            # 序列化用户数据
            user_serializer = UserSerializer(instance=user)

            # 返回响应
            return Response({
                "results": {
                    'token': str(access_token),
                    'user': user_serializer.data
                },
                'message': "登录成功"
            }, status=status.HTTP_200_OK)
        else:
            # 登录失败
            return Response({'error': '用户名或密码错误'}, status=status.HTTP_400_BAD_REQUEST)


class UserLogoutView(APIView):
    permission_classes = [AllowAny]

    def get(self, request, *args, **kwargs):
        # 使用 Django 内置的 LogoutView 来处理注销
        logout_view = LogoutView.as_view()
        response = logout_view(request, *args, **kwargs)
        # 您可以根据需要修改响应，例如添加自定义消息
        return Response({'message': '您已成功注销。'}, status=response.status_code)
